//
//  BatchconversionViewController.m
//  SafeFoodManagerDemo
//
//  Created by pc on 2018/3/22.
//  Copyright © 2018年 bob. All rights reserved.
//

#import "BatchconversionViewController.h"
#import "ConversionPriceTableViewCell.h"
#import "BatchConversionHeader.h"
#import "OrderReqModel.h"
#import "MBProgressHUD+XY.h"

@interface BatchconversionViewController ()<priceDelegate>
//批量更改价格模型的索引数组。
@property(nonatomic,strong)NSMutableArray *indexArray;
//批量更改价格的模型。
@property(nonatomic,strong)NSMutableArray *DataArray;

@property(nonatomic,strong)UILabel *label;

@property(nonatomic,copy)NSString*SearchKeyWord;
@end

@implementation BatchconversionViewController

- (void)viewDidLoad {
   [super viewDidLoad];
    
    self.Reqmodel = [[OrderReqModel alloc]init];
   [self setUpTableview];
    
    
}

-(NSMutableArray*)indexArray{
    if (!_indexArray) {
      
       _indexArray = [NSMutableArray array];
    }
    
    return _indexArray;
    
}

-(NSMutableArray*)DataArray{
    if (!_DataArray) {
        _DataArray = [NSMutableArray array];
    }
    
    return _DataArray;
    
}


-(void)setUpTableview{
    
    
    //[self.dataArr addObjectsFromArray:@[@"1",@"2",@"3"]];

    
    NSLog(@"%@",NSStringFromCGRect(self.homeTableView.frame));
    self.navigationItem.title = @"批量改价";
    self.homeTableView.estimatedRowHeight=70;
    BatchConversionHeader *view1 =[BatchConversionHeader loadBatchConversionHeader];
    self.label = view1.countLabel;
    self.homeTableView.tableHeaderView = view1;
    
    //self.homeTableView.frame= CGRectMake(0, 0, 414, 563);
    
    
    [self.homeTableView registerNib:[UINib nibWithNibName:@"ConversionPriceTableViewCell" bundle:nil] forCellReuseIdentifier:@"ConversionPrice"];
    
    [self.homeTableView.mj_header beginRefreshing];
    
    //导入成功通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Assignmentnote) name:@"SaveSuccessnote" object:nil];
    
    
    
}


- (void)Assignmentnote
{
    [self.homeTableView.mj_header beginRefreshing];
}

//加载数据。

-(void)loadDatas
{
    [self showLoadingAnimation];
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
    dict[@"shopId"] =[self getShopID];
    dict[@"params"] = self.Reqmodel.params;
    
    
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/productBatchList.json" andrequestTime:5 andParams:dict andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        
        DLog(@"请求到的数据--%@",responseObject);
        [self stopLoadingAnimation];
        
         PriceListMode *InforModel=[PriceListMode mj_objectWithKeyValues:responseObject];
        
        
        if (responseStatus==1) {
            //请求成功
             //self.TotalNum=[NSString stringWithFormat:@"一共找到%ld个%@",InforModel.totalRecord,@"商品"];
            self.label.text = [NSString stringWithFormat:@"一共找到%ld个%@",InforModel.totalRecord,@"商品"];
            //NSLog(@"%@",[HelpWay dictionaryToJSON:responseObject]);
            
            if (self.dataArr.count>0) {
                [self.dataArr removeAllObjects];
            }
            [self.dataArr addObjectsFromArray:InforModel.data];
            self.homeTableView.tableFooterView.hidden = YES;
             [self.homeTableView.mj_footer endRefreshingWithNoMoreData];
            
            [self.homeTableView reloadData];
            
         
            
            [self NetRequestSuccess:self scrollView:self.homeTableView];
            
        }else if (responseStatus==0||responseStatus==2)
        {
            
            
            [self NetRequestFail:self scrollView:self.homeTableView msg:message];
            
            self.Type=TBReqFalie;
            
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
        }
        
    }];
    
    
}

#pragma mark-跳转事件
-(void)PushChangeStatueVC
{
    BOOL isSelf=self.Reqmodel.shopId==0?YES:NO;
    
    BaseSearchChooseViewController *Choose=[[BaseSearchChooseViewController alloc]init];
    
    Choose.ReqStr=[SearchAndChooseManager getChooseUrlWithType:ProductsListType];
    
    Choose.CustomArr=[SearchAndChooseManager GetChooseDateWithType:ProductsListType andIsLookSelf:isSelf];
    
    Choose.SearchPlace=self.searchName;
    
    Choose.KeyWord=self.SearchKeyWord;
    
    Choose.SureBlock=^(NSString *paras,NSString*keyword)
    {
        
        
        
        self.SearchKeyWord=keyword;
        
        self.Reqmodel.params=paras;
        
        [self.homeTableView.mj_header beginRefreshing];
    };
    
    [self.navigationController pushViewController:Choose animated:YES];
}

#pragma mark-空白页点击事件
- (void)actionTapEmptyDataSetNodataView
{
    [self.homeTableView.mj_header beginRefreshing];
    
}


/**
 *  MJ头部刷新(封装层方法, 需要子类继承或者重写)
 */
- (void)actionMJHeaderRefresh
{
   
    
    [self.homeTableView.mj_footer resetNoMoreData];
    
    [self loadDatas];
}

/**
 *  MJ底部加载(封装方法, 需要子类继承或者重写)
 */
- (void)actionMJFooterLoadMore
{
   
    
   // [self loadDatas];
}

//新增事件.

-(void)addNewgoods
{
    DLog("点击了")
    [self getData];
    NSData *data=[NSJSONSerialization dataWithJSONObject:self.DataArray options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonStr=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
   
    [self showLoadingAnimation];
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
    dict[@"shopId"] = [self getShopID];
    
    dict[@"postData"] = jsonStr;
    
    BaseReqApi *api=[[BaseReqApi alloc]initWithRequestUrl:@"/index.php/FoodCheckApi/productBatchEdit.json" andrequestTime:5 andParams:dict andRequestMethod:YTKRequestMethodPOST andCache:NO andCacheTime:0 andPostToken:YES];
    
    [api StarRequest:^(TBResponseStatus responseStatus, NSString *message, id responseObject) {
        
        DLog(@"请求到的数据--%@",responseObject);
        [self stopLoadingAnimation];
        NSString *str = responseObject[@"msg"];
        NSInteger data = responseObject[@"data"];
        NSLog(@"%ld条数据%@",(long)data,str);
        NSString *sucStr =[NSString stringWithFormat:@"%ld条数据%@,(long)data,str"];
        
      
        
        
        
        
        
        if (responseStatus==1) {
            //请求成功
            [self.homeTableView.mj_footer endRefreshingWithNoMoreData];
            NSLog(@"%@",[HelpWay dictionaryToJSON:responseObject]);
            
            [self.indexArray removeAllObjects];
            [self.DataArray removeAllObjects];
            [self loadDatas];
            
           // [self.homeTableView reloadData];
            
            
            
            [self NetRequestSuccess:self scrollView:self.homeTableView];
            
        }else if (responseStatus==0||responseStatus==2)
        {
            
            
            [self NetRequestFail:self scrollView:self.homeTableView msg:message];
            
            self.Type=TBReqFalie;
            
        }else{
            //404需要重新登录了
            
            [UIAlertView bk_showAlertViewWithTitle:message message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
                
                if (buttonIndex==1) {
                    
                    [self GotoLoginVC];
                }
                
            }];
        }
        
    }];
    
    
    
    
    
    
}
#pragma mark-tablevie代理方法


-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ConversionPriceTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ConversionPrice"];
    cell.delegate = self;
    
    cell.data = self.dataArr[indexPath.row];
    return cell;
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return UITableViewAutomaticDimension;
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)costPrice:(NSString*)costPrice costIndex :(NSInteger)index{
    
    NSLog(@"%@---%ld",costPrice,index);
    
    
    //根据index取出model;
   PriceListData *mode = self.dataArr[index];
    NSString *indexStr = [NSString stringWithFormat:@"%ld",index];
    
   mode.price = [costPrice doubleValue];
    if(! [self.indexArray containsObject:indexStr]){
        
       
        [self.indexArray addObject:indexStr];
        
        
    };
    
}


//获取所有需要上传的接口数组。
- (void)salePrice:(NSString*)salePrice costIndex :(NSInteger)index{
    
    
    
    NSLog(@"%@---%ld",salePrice,index);
    
    //根据index取出model;
    PriceListData *mode = self.dataArr[index];
    NSString *indexStr = [NSString stringWithFormat:@"%ld",index];

        mode.salePrice = [salePrice doubleValue];
        if(! [self.indexArray containsObject:indexStr]){
            
            
            [self.indexArray addObject:indexStr];
            
            
        };
  
   
    
    
    
}
-(void)getData{
    
    for (NSString* indexStr in self.indexArray) {
        
        PriceListData *mode = self.dataArr[[indexStr integerValue]];
        NSDictionary *dic  =  mode.mj_keyValues;
        
        [self.DataArray addObject:dic];
    }
    
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    
     UIView *view1 = [UIView new];
    view1.frame = CGRectMake(0, 0, 400, 40);
    view1.backgroundColor = [UIColor redColor];
 
    return view1;
    
    
}


//获取shopID;

-(NSString*)getShopID{
    NSString * shopID;
    if ([self getUserType]==1) {
        shopID =[NSString stringWithFormat:@"%ld",[LoginStatuesModel shopId]];
    }else{
        shopID  = [NSString stringWithFormat:@"%ld",self.shopId];
    }
    
    return  shopID;
    
    
}

@end
